<template>
  <div class="login-page">
    <div class="title">登录页面</div>
    <div class="form">
      <div class="username">
        <p>用户名:</p>
        <div class="box">
          <input
            v-model="username"
            type="text"
            name=""
            id=""
            placeholder="请输入用户名"
            @blur="username === '' ? (isShowName = true) : (isShowName = false)"
            @input="
              username === '' ? (isShowName = true) : (isShowName = false)
            "
          />
          <div v-show="isShowName">不能为空</div>
        </div>
      </div>
      <div class="password">
        <p>密码:</p>
        <div class="box">
          <input
            v-model="password"
            type="password"
            name=""
            id=""
            placeholder="请输入密码"
            @blur="password === '' ? (isShowPw = true) : (isShowPw = false)"
            @input="password === '' ? (isShowPw = true) : (isShowPw = false)"
          />
          <div v-show="isShowPw">不能为空</div>
        </div>
      </div>
      <button class="submit" @click="login">登录</button>
    </div>
    <router-link to="/register">去注册</router-link>
  </div>
</template>

<script>
import { loginApi } from '@/apis/user'

export default {
  name: 'login-page',
  data () {
    return {
      isShowName: false,
      isShowPw: false,
      username: '',
      password: ''
    }
  },
  methods: {
    async login () {
      const data = { username: this.username, password: this.password }
      try {
        const {
          data: {
            data: { token }
          }
        } = await loginApi(data)
        localStorage.setItem('userToken', token)
        this.$toast('登录成功')
        this.password = this.username = ''
        this.$router.push('/home')
      } catch (err) {
        if (err.response) {
          this.$toast(err.response.data.message)
        } else {
          this.$toast('error')
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.log in-page {
  background-color: #f7f8fa;
}

.title {
  height: 60px;
  text-align: center;
  font-size: 20px;
  line-height: 60px;
  background-color: #fff;
}

.form {
  padding: 0px 15px;
  .username,
  .password {
    display: flex;
    justify-content: left;
    align-items: center;
    height: 60px;
    background-color: #fff;
    p {
      width: 50px;
      height: 60px;
      font-size: 20px;
      line-height: 60px;
    }
    .box {
      input {
        height: 30px;
        border: 0px solid #000;
        margin-left: 40px;
      }
      div {
        margin-left: 40px;
        color: red;
      }
    }
  }
  .submit {
    display: block;
    width: 100%;
    background-color: #1989fa;
    height: 50px;
    line-height: 50px;
    border: 0px solid #000;
    border-radius: 25px;
  }
}

a {
  display: block;
  text-align: right;
  margin-right: 30px;
  margin-top: 20px;
}
</style>
